package com.cloudxingkong.dianyinke.NewTeacher.Utils;

import android.os.Environment;
import android.os.StatFs;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * SDCard工具类
 */
public class SDCardHelper {
	/*
	 * 判断SDcard是否可用
	 */
	public static boolean isSDCardMounted(){
		return Environment.getExternalStorageState().equals("mounted");
	}
	/*
	 * 返回SDcard的目录
	 */
	public static String getSDCardPath(){
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}
	/*
	 * 返回SDcard的大小
	 */
	public static float getSDCardSize(){
		if (isSDCardMounted()) {
			StatFs fs=new StatFs(getSDCardPath());
			long size=fs.getBlockSize();
			long count=fs.getBlockCount();
			return size*count/1024/1024;
		}
		return 0;
	}
	/*
	 * 返回剩余空间的大小
	 */
	public static float getSDCardFreeSize(){
		if (isSDCardMounted()) {
			StatFs fs=new StatFs(getSDCardPath());
			long size=fs.getBlockSize();
			long count=fs.getFreeBlocks();
			return size*count/1024/1024;
		}
		return 0;
	}
	/*
	 * 保存文件到SDCard
	 */
	public static boolean saveFileToSDCard(byte[] data,String dir,String filename){
		if (isSDCardMounted()) {
			//创建在sdcard上的存储路径
			File file=new File(getSDCardPath()+File.separator+dir);
			if (!file.exists()) {
				file.mkdirs(); //如果不存在就创建文件夹
			}
			if (getSDCardSize()>(data.length/1024/1024)) { //空间是否可用
				FileOutputStream fos=null;
				try {
					fos=new FileOutputStream(new File(file,filename));
					fos.write(data);
					return true;
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					if (fos!=null) {
						try {
							fos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return false;
	}
	
	/*
	 * 从SDCard读取文件
	 */
	public static byte[] loadFileFromSDCard(String filename){
		if (isSDCardMounted()) {
			File file=new File(getSDCardPath()+File.separator+filename);
			if(file.exists()){
				FileInputStream fis=null;
				ByteArrayOutputStream baos=null;
				try {
					fis=new FileInputStream(file);
					baos=new ByteArrayOutputStream();
					byte[] b=new byte[1024];
					int len=0;
					while ((len=fis.read(b))!=-1) {
						baos.write(b, 0, len);
					}
					return baos.toByteArray();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
